const mysql = require('mysql2/promise'),
      log   = console.log,
      Koa   = require('koa'),
      app   = new Koa(),
      Router = require('koa-router'),
      router = new Router(),
      fs    = require('fs'),
      path  = require('path'),
      cors  = require('koa2-cors'),
      http  = require('http'),
      https = require('https'),
      bodyparser = require('koa-bodyparser'),
      hq = require('./shop.js'),
      hq1 = require('./concern_shop.js'),
      hq2 = require('../management/shouye.js');
const options = {
    key:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.key')),
    cert:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.crt'))
}

app.use(bodyparser());

app.use(cors({
    origin: function (ctx) {
        if (ctx.url === '/shopdel') {
          return "*"; // 允许来自所有域名请求
        }
        return 'http://localhost:8000'; // 这样就能只允许 http://localhost:8080 这个域名的请求了 
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
//顺序
function sortx(a,b){
  return Date.parse(b.date)-Date.parse(a.date);
}
//反序
function sortj(a,b){
  return Date.parse(a.date)-Date.parse(b.date);
}
//id筛选
function food(data,id){
    for(var i = 0;i < data.length;i++){
       if(data[i].food!=id){
           data.splice(i,1);
              i-=1;
       }
    }
    return data;
}
//删空
function climg (obj, fn) {
  for (var i in obj) {
      if (typeof obj[i] === 'object') {
            climg(obj[i], fn)
      }
      if (fn(obj[i])) {
          delete obj[i]
      }
  }
}
 
function delimg (foo) {
    if (typeof foo === 'object') {
        for (var i in foo) {
             return false
        }
        return true
    } else {
        return foo === '' || foo === null || foo === undefined
    }
}
//调用 climg(imgs,delimg) 
router.get('/home/api',async (ctx) => {
    let arr = await hq.getid_home();
    //arr.sort(sortx);
    console.log(arr);
    ctx.body = JSON.stringify(arr);
})

router.get('/shop/api',async (ctx) => {
    let {pageSize,pageNum} = ctx.request.query;
    let start = pageNum*pageSize;
    let arr = await hq.getid_shop(start,pageSize);
    let arr1 = await hq.getnum();
    let obj = new Object(); 
    obj.data = arr;
    obj.nums = arr1[0].count;
    console.log(obj);
    ctx.body = JSON.stringify(obj);

})

router.get('/shop/query',async (ctx) => {
    let {name} = ctx.request.query;
    //log(name);
    let arr = await hq.getname_shop(name);
    console.log(arr);
    ctx.body = JSON.stringify(arr);
})

router.get('/shop/api/details',async (ctx) =>{
    let {user_id,shop_id} = ctx.request.query;
    let arr = await hq.getid_shop_details(shop_id);
    let arr1 = await hq.getuser_shop_state(user_id,shop_id);
    let state; 
    if(arr1.length==0) state = 2;
    else state = arr1[0].state;
    let a = await hq1.getshop_num(shop_id,1);
    let num = a.length;
    var arr2=[];
    arr2.push({
      "shop_id":arr[0].id,
      "shop_name": arr[0].shop_name,
      "shop_tel":arr[0].shop_tel,
      "shop_addr":arr[0].shop_addr,
      "shop_jwd":arr[0].shop_jwd,
      "shop_img":arr[0].shop_img,
      "shop_http":'http://fourgoldhua.cn:3001',
      "shop_mtid":arr[0].shop_mtid,
      "shop_annoumcementinfo":arr[0].shop_announcementinfo,
      "state":state,
      "num":num
    })
    console.log(arr2);
    ctx.body = JSON.stringify(arr2);
})

router.post('/shop/insert',async (ctx) =>{
    let {id,name,tel,addr,jwd,img,mtid,r1,r2,r3,announcementinfo} = ctx.request.query;
    await hq.insert_shop(id,name,tel,addr,mtid,r1,r2,r3,announcementinfo);
    
})

router.post('/shopdel',async (ctx) =>{
  //log(ctx.request.body);
  //let {id} = ctx.request.query;
  let id= ctx.request.body.id;
  console.log(id);
  await hq.delid_shop(id);
  await hq.delconcern_shop(id);
  let arr = await hq2.getshop();
  ctx.body = JSON.stringify(arr);
})

process.on('unhandledRejection',(reason,p) => {
    console.log('Unhandled Rejection at:Promise',p,'reason:',reason);
});

app.use(router.routes())
   .use(router.allowedMethods());

https.createServer(options,app.callback()).listen(2228);
//app.listen(2228);
